package com.jojo.bubble.utils;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.util.StringUtils;
import sun.font.FontDesignMetrics;

/**
 * @Author JoJo
 * @Date 2023/8/8 14:47
 * @Description
 * @Version 1.0
 */
public class QRCodeGenerator {
    public static final int QRCODE_SIZE = 300; // 二维码尺寸，宽度和高度均是320
    public static final String FORMAT_TYPE = "PNG"; // 二维码图片类型
    public static String getCode(String code, int id) {
        String url = "";

        String data = "https://ppj.renniyou.com.cn/h5/#/pages/index/index?devId=" + id; // 要编码的数据，包括参数

        int width = 300; // 二维码图片的宽度
        int height = 320; // 二维码图片的高度
        String format = "png"; // 二维码图片的格式

        // 设置编码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        try {
            // 创建二维码写入器对象
            QRCodeWriter writer = new QRCodeWriter();

            // 创建比特矩阵对象，表示二维码的黑白像素点
            BitMatrix matrix = writer.encode(data, BarcodeFormat.QR_CODE, width, height, hints);

            // 创建缓冲图像对象
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            // 填充图像的像素点颜色
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int pixelColor = matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF; // 黑色和白色像素点颜色
                    image.setRGB(x, y, pixelColor);
                }
            }
            String bottomText = code.substring(code.length()-6);

            if (StringUtils.hasText(bottomText)) {
                addFontImage(image, bottomText);
            }
            String fileName = code + ".png";

            // 保存二维码图片到文件
            File outputFile = new File("/root/source/images/"+fileName);
//            File outputFile = new File("D:\\"+fileName);
            ImageIO.write(image, format, outputFile);

//            System.out.println("二维码图片生成成功！");
            url = "https://ppj.renniyou.com.cn/images/" + fileName;
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
        return url;
    }

    public static void addFontImage(BufferedImage source, String declareText) {
        //生成image
        int defineWidth = QRCODE_SIZE;
        int defineHeight = 20;
        BufferedImage textImage = new BufferedImage(defineWidth, defineHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) textImage.getGraphics();
        //开启文字抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,   RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, defineWidth, defineHeight);
        g2.setPaint(Color.BLACK);
        FontRenderContext context = g2.getFontRenderContext();
        //部署linux需要注意 linux无此字体会显示方块
        Font font = new Font("宋体", Font.BOLD, 15);
        g2.setFont(font);
        LineMetrics lineMetrics = font.getLineMetrics(declareText, context);
        FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);
        float offset = (defineWidth - fontMetrics.stringWidth(declareText)) / 2;
        float y = (defineHeight + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;
        g2.drawString(declareText, (int) offset, (int) y);

        Graphics2D graph = source.createGraphics();
        //开启文字抗锯齿
        graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,   RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        //添加image
        int width = textImage.getWidth(null);
        int height = textImage.getHeight(null);

        Image src = textImage;
        graph.drawImage(src, 0, QRCODE_SIZE - 8, width, height, Color.WHITE, null);
        graph.dispose();
    }


    public static void main(String[] args) {
        String data = "http://ppj.renniyou.com.cn?devId="; // 要编码的数据，包括参数

        int width = 300; // 二维码图片的宽度
        int height = 320; // 二维码图片的高度
        String format = "png"; // 二维码图片的格式
        String code = "861658068917577";
        // 设置编码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        try {
            // 创建二维码写入器对象
            QRCodeWriter writer = new QRCodeWriter();

            // 创建比特矩阵对象，表示二维码的黑白像素点
            BitMatrix matrix = writer.encode(data, BarcodeFormat.QR_CODE, width, height, hints);

            // 创建缓冲图像对象
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            // 填充图像的像素点颜色
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int pixelColor = matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF; // 黑色和白色像素点颜色
                    image.setRGB(x, y, pixelColor);
                }
            }
            String bottomText = code.substring(code.length()-6);
            if (StringUtils.hasText(bottomText)) {
                addFontImage(image, bottomText);
            }
            String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".png";
            // 保存二维码图片到文件
            File outputFile = new File("D:\\"+fileName);
            ImageIO.write(image, format, outputFile);

            System.out.println("二维码图片生成成功！");
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
    }
}
